#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
数据可视化大屏项目启动脚本
"""

import os
import sys
import subprocess
import pymysql
from config import Config

def check_python_version():
    """检查Python版本"""
    print("🔍 检查Python版本...")
    version = sys.version_info
    if version.major < 3 or (version.major == 3 and version.minor < 7):
        print("❌ Python版本过低，需要Python 3.7或更高版本")
        print(f"当前版本: {version.major}.{version.minor}.{version.micro}")
        return False
    print(f"✅ Python版本: {version.major}.{version.minor}.{version.micro}")
    return True

def install_requirements():
    """安装依赖包"""
    print("📦 检查并安装依赖包...")
    try:
        subprocess.check_call([sys.executable, "-m", "pip", "install", "-r", "requirements.txt"])
        print("✅ 依赖包安装完成")
        return True
    except subprocess.CalledProcessError:
        print("❌ 依赖包安装失败")
        return False

def check_database_connection():
    """检查数据库连接"""
    print("🗄️ 检查数据库连接...")
    try:
        conn = pymysql.connect(
            host=Config.MYSQL_HOST,
            port=Config.MYSQL_PORT,
            user=Config.MYSQL_USER,
            password=Config.MYSQL_PASSWORD,
            charset='utf8mb4'
        )
        
        # 检查数据库是否存在
        cursor = conn.cursor()
        cursor.execute(f"SHOW DATABASES LIKE '{Config.MYSQL_DATABASE}'")
        result = cursor.fetchone()
        
        if not result:
            print(f"⚠️ 数据库 '{Config.MYSQL_DATABASE}' 不存在，正在创建...")
            cursor.execute(f"CREATE DATABASE {Config.MYSQL_DATABASE} DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci")
            print(f"✅ 数据库 '{Config.MYSQL_DATABASE}' 创建成功")
        
        cursor.close()
        conn.close()
        print("✅ 数据库连接正常")
        return True
        
    except Exception as e:
        print(f"❌ 数据库连接失败: {str(e)}")
        print("请检查以下配置:")
        print(f"  - 主机: {Config.MYSQL_HOST}")
        print(f"  - 端口: {Config.MYSQL_PORT}")
        print(f"  - 用户名: {Config.MYSQL_USER}")
        print(f"  - 密码: {Config.MYSQL_PASSWORD}")
        return False

def init_database():
    """初始化数据库"""
    print("🗃️ 初始化数据库...")
    try:
        conn = pymysql.connect(
            host=Config.MYSQL_HOST,
            port=Config.MYSQL_PORT,
            user=Config.MYSQL_USER,
            password=Config.MYSQL_PASSWORD,
            database=Config.MYSQL_DATABASE,
            charset='utf8mb4'
        )
        
        cursor = conn.cursor()
        
        # 读取并执行schema.sql
        with open('database/schema.sql', 'r', encoding='utf-8') as f:
            schema_sql = f.read()
        
        # 分割SQL语句并执行
        statements = schema_sql.split(';')
        for statement in statements:
            statement = statement.strip()
            if statement:
                cursor.execute(statement)
        
        # 读取并执行data.sql
        with open('database/data.sql', 'r', encoding='utf-8') as f:
            data_sql = f.read()
        
        statements = data_sql.split(';')
        for statement in statements:
            statement = statement.strip()
            if statement:
                cursor.execute(statement)
        
        conn.commit()
        cursor.close()
        conn.close()
        
        print("✅ 数据库初始化完成")
        return True
        
    except Exception as e:
        print(f"❌ 数据库初始化失败: {str(e)}")
        return False

def check_files():
    """检查必要文件"""
    print("📁 检查项目文件...")
    required_files = [
        'app.py',
        'config.py',
        'requirements.txt',
        'database/schema.sql',
        'database/data.sql',
        'templates/index.html',
        'static/css/style.css',
        'static/js/charts.js'
    ]
    
    missing_files = []
    for file_path in required_files:
        if not os.path.exists(file_path):
            missing_files.append(file_path)
    
    if missing_files:
        print("❌ 缺少以下文件:")
        for file_path in missing_files:
            print(f"  - {file_path}")
        return False
    
    print("✅ 所有必要文件存在")
    return True

def main():
    """主函数"""
    print("=" * 60)
    print("🚀 数据可视化大屏项目启动器")
    print("=" * 60)
    
    # 检查Python版本
    if not check_python_version():
        return
    
    # 检查项目文件
    if not check_files():
        return
    
    # 安装依赖
    if not install_requirements():
        return
    
    # 检查数据库连接
    if not check_database_connection():
        return
    
    # 初始化数据库
    if not init_database():
        return
    
    print("=" * 60)
    print("🎉 环境检查完成，启动应用...")
    print("=" * 60)
    
    # 启动Flask应用
    try:
        from app import app
        print("✅ 应用启动成功!")
        print("🌐 访问地址: http://localhost:5000")
        print("📊 数据大屏: http://localhost:5000")
        print("=" * 60)
        print("按 Ctrl+C 停止应用")
        print("=" * 60)
        
        app.run(debug=True, host='0.0.0.0', port=5000)
        
    except KeyboardInterrupt:
        print("\n👋 应用已停止")
    except Exception as e:
        print(f"❌ 应用启动失败: {str(e)}")

if __name__ == "__main__":
    main() 